package com.ncpowernode.task;

import com.ncpowernode.pojo.Item;
import com.ncpowernode.service.ItemService;
import com.ncpowernode.utils.HttpUtils;
import jdk.nashorn.internal.ir.ContinueNode;
import org.apache.http.client.utils.HttpClientUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Resource
    private HttpUtils httpUtils;

    @Resource
    private ItemService itemService;

    // 当下载任务完成之后，间隔多长时间进行下一次任务
    @Scheduled(fixedDelay = 100*1000)
    public void itemTask() throws Exception{

        // 声明需要解析的初始地址
        String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&wq=%E6%89%8B%E6%9C%BA&pvid=90993a2e94e1422aa7e10aaaf41e1378&s=361" +
                "&click=0&page=";
        for(int i=1; i<10; i+=2){
            String realUrl = url + i;
            String html = httpUtils.doGetHtml(realUrl);

            // 解析页面，获取商品数据并存储
            parse(html);

        }

        System.out.println("手机数据抓取完成！现在时间:" + LocalTime.now().toString());

    }
    private void parse(String html){

        Document doc = Jsoup.parse(html, "utf-8");
        // 获取spu
        Elements liElements = doc.select("div#J_goodsList > ul > li");

        liElements.forEach(liElement->{
            String spu = liElement.attr("data-sku");// li 上的sku是初始值是和spu一样的
            // 获取sku
            Elements skuElements = liElement.select("li.ps-item");
            List<String> skus = new ArrayList<String>();
            for (Element skuElement : skuElements) {
                Elements imgs = skuElement.select("img[data-sku]");
                for (Element img : imgs) {
                    String sku = img.attr("data-sku");
                    // 根据sku查询商品信息
                    Item item = Item.builder().sku(sku).build();
                    List<Item> itemList = itemService.findAll(item);
                    if(!itemList.isEmpty()){
                        continue;
                    }
                    // 如果商品存在，就进行下一个循环，这商品不保存，因为商品已存在
                    item.setSpu(spu);

                    // 获取商品的详情链接
                    String itemUrl = "https://item.jd.com/" + sku + ".html";
                    item.setUrl(itemUrl);

                    String imgSrc = "https:" + img.attr("data-lazy-img");
                    imgSrc = imgSrc.replace("/n7/", "/n1/");
                    String imgName = httpUtils.doGetImage(imgSrc);
                    item.setPic(imgName);

                    // 进入到手机详情页后去获取页面的doc
                    String itemHtml = httpUtils.doGetHtml(itemUrl);
                    // itemHtml = HtmlUtils.htmlEscape(itemHtml);
                    Document itemDoc = Jsoup.parse(itemHtml, "utf-8");

                    String price = liElement.select("div.p-price i").first().text();
                    // String price = itemDoc.select("div.summary-price-wrap span.p-price span").get(1).text();
                    if(!price.isEmpty()) {
                        Double realPrice = Double.parseDouble(price);
                        item.setPrice(realPrice);
                    }

                    Elements sku_name = itemDoc.select("title");
                    String title = sku_name.size()>0?sku_name.first().text():"";
                    item.setTitle(title);
                    // item.setTitle();
                    item.setCreated(new Date());
                    item.setUpdated(item.getCreated());

                    // 保存数据到数据库中
                    itemService.save(item);
                }
            }

        });
    }

}
